package com.car.controller.check;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.car.entity.*;
import com.car.service.car.CarServiceImpl;
import com.car.service.impl.TReturn.TReturnServiceImpl;
import com.car.service.impl.check.checkServiceImpl;
import com.car.service.order.OrderServiceImpl;
import com.car.util.ResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class checkController {

    @Autowired
    checkServiceImpl checkServiceimpl;
    @Autowired
    OrderServiceImpl orderServiceImpl;
    @Autowired
    CarServiceImpl carServiceImpl;
    @Autowired
    TReturnServiceImpl tReturnServiceImpl;

    @RequestMapping("/tochecklist")
    public ModelAndView tochecklist(){
        return new ModelAndView("check");
    }

    @RequestMapping("/toALIPay")
    public ModelAndView toALIPay(){
        return new ModelAndView("/User/index");
    }

    @RequestMapping("/checklist")
    @ResponseBody
    public Map checklist(String checkId, String carIdCard, String PageNum, String PageSize){
        Integer pageNum = Integer.valueOf(PageNum);
        Integer pageSize = Integer.valueOf(PageSize);

        Map<String,Object> map = new HashMap<>();
        map.put("checkId",checkId);
        map.put("carIdCard",carIdCard);
        map.put("pageNum",pageNum);
        map.put("pageSize",pageSize);

        Page page = checkServiceimpl.selectlistquery(map);
        map.put("page",page);
        map.put("totalPage",page.getTotal()%page.getSize()==0?
                        page.getTotal()/page.getSize() :
                        (page.getTotal()/page.getSize()+1)
                );
        return map;
    }

    @RequestMapping("/addcheck")
    @ResponseBody
    public ResultMsg addCheck(Check check){
        ResultMsg resultMsg = checkServiceimpl.addCheck(check);
        return resultMsg;
    }

    @RequestMapping("/updateCheck")
    @ResponseBody
    public ResultMsg updateCheck(Check check){
        ResultMsg resultMsg = checkServiceimpl.updateCheck(check);
        if(resultMsg.getFlag()==1){
          int flag = orderServiceImpl.updateOrderState(check.getOrderID(),7);
          if(flag ==1 ){
              resultMsg.setFlag(1);
              resultMsg.setMsg(resultMsg.getMsg()+"，修改订单状态成功");
          }else {
              resultMsg.setFlag(0);
              resultMsg.setMsg(resultMsg.getMsg()+"，修改订单状态失败");
          }
        }
        return resultMsg;
    }

    @RequestMapping("/TwopdateCheck")
    @ResponseBody
    public ResultMsg TwopdateCheck(Check check){
        ResultMsg resultMsg = checkServiceimpl.updateCheck(check);
        if(resultMsg.getFlag()==1){
            int flag = orderServiceImpl.updateOrderState(check.getOrderID(),8);
            if(flag ==1 ){
                resultMsg.setFlag(1);
                resultMsg.setMsg(resultMsg.getMsg()+"，修改订单状态成功");
            }else {
                resultMsg.setFlag(0);
                resultMsg.setMsg(resultMsg.getMsg()+"，修改订单状态失败");
            }
        }
        return resultMsg;
    }

    @RequestMapping("/delcheck")
    @ResponseBody
    public ResultMsg delcheck(Check check){
        ResultMsg resultMsg = checkServiceimpl.delCheck(check);
        return resultMsg;
    }

    @RequestMapping("/checkquery")
    @ResponseBody
    public ModelAndView checkquery(Check check,HttpSession session){
        ModelAndView mv = new ModelAndView();
        ResultMsg resultMsg = checkServiceimpl.checkquery(check);
        Check check1 = (Check) resultMsg.getEntityObj();
        if(session.getAttribute("use")==null){
            resultMsg.setMsg("未登录系统，请重新登录");
            mv.setViewName("result");
            mv.addObject("resultMsg",resultMsg);
            return mv;
        }
            User user = (User) session.getAttribute("use");

        check1.setUserId(user.getUserId());
        resultMsg.setEntityObj(check1);
        mv.setViewName("check-Add");
        mv.addObject("result",resultMsg);
        return mv;
    }

    @RequestMapping("/SeecheckEvent")
    @ResponseBody
    public ModelAndView SeecheckEvent(Check check){
        ModelAndView mv = new ModelAndView();
        ResultMsg resultMsg = checkServiceimpl.checkquery(check);
        mv.setViewName("check-see");
        mv.addObject("result",resultMsg);
        return mv;
    }

    @RequestMapping("/seeCheckquery")
    @ResponseBody
    public ModelAndView seeCheckquery(Check check){
        ModelAndView mv = new ModelAndView();
        ResultMsg resultMsg = checkServiceimpl.checkquery(check);
        mv.setViewName("check-see");
        mv.addObject("result",resultMsg);
        return mv;
    }

    @RequestMapping("/jieSuanOrder")
    @ResponseBody
    public ModelAndView jieSuanOrder(String orderId){
        ModelAndView mv = new ModelAndView();
        Check check = checkServiceimpl.selectCheckbyOrderId(orderId);
        Car car = carServiceImpl.getCarByID(check.getCarId());
        Order order = orderServiceImpl.selectById(check.getOrderID());
        Map<String,Object> map = jieSuanJE(check,car,order);
        map.put("check",check);
        map.put("car",car);
        map.put("order",order);
        mv.addObject("map",map);
        mv.setViewName("checkOne");
        return mv;
    }

    @RequestMapping("/toCheckJIeSuan")
    @ResponseBody
    public ModelAndView toCheckJIeSuan(String orderId){
        ModelAndView mv = new ModelAndView();
        Check check = checkServiceimpl.selectCheckbyOrderId(orderId);
        Car car = carServiceImpl.getCarByID(check.getCarId());
        Order order = orderServiceImpl.selectById(check.getOrderID());
        Map<String,Object> map = jieSuanJE(check,car,order);
        map.put("check",check);
        map.put("car",car);
        map.put("order",order);
        mv.addObject("map",map);
        mv.setViewName("checkJIeSuan");
        return mv;
    }

    public Map<String,Object> jieSuanJE(Check check,Car car,Order order){
        Map<String,Object> map = new HashMap<>();
        //车审后应该赔偿的总价
        double CarSunP = check.getCheckPrice();
        //判断汽车型号
        int flag = car.getCarDriverType();
        //使用前后燃料量
        double startY = 0;
        double endY = 0;
        //该订单油价
        double OiP;
        //该订单电价
        double ElP;
        //该订单油电总价
        double OEP = 0;
        if(flag==0){
            startY = order.getOrderStartCarOilValue();
            endY = order.getOrderEndCarOilValue();
            OiP = order.getOrderOilPrice();
            OEP = (startY-endY)*OiP;
        }else if(flag==1){
            startY = order.getOrderStartCarElectriclValue();
            endY = order.getOrderEndCarElectriclValue();
            OiP = order.getOrderElectricPrice();
            OEP = (startY-endY)*OiP;
        }else if(flag==2){

            double OstartY = order.getOrderStartCarOilValue();
            double OendY = order.getOrderEndCarOilValue();
            double OOiP = order.getOrderOilPrice();

            double EstartY = order.getOrderStartCarElectriclValue();
            double EendY = order.getOrderEndCarElectriclValue();
            double EOiP = order.getOrderElectricPrice();
            OEP = (OstartY-OendY)*OOiP+(EstartY-EendY)*EOiP;
        }
        //获取该汽车的服务费
        double carHygieneMoney  = car.getCarHygieneMoney();
        //获取租借天数
        Date startDay = order.getOrderReserveStartDate();
        Date endDay = order.getOrderEndDate();
        int days = (int) ((endDay.getTime()-startDay.getTime())%(60*60*24*1000)>(60*1000*60*2)?(endDay.getTime()-startDay.getTime())/(60*60*24*1000)+1:(endDay.getTime()-startDay.getTime())/(60*60*24*1000));
        //获取汽车每天的租金
        int carPrice = car.getCarPrice();
        double AlldayMoney = carPrice*days;
        //返回
        //车审后应该赔偿的总价
        map.put("CarSunP",Double.valueOf(String.format("%.2f",CarSunP)));
        //该订单油电总价
        map.put("OEP",OEP);
        //获取该汽车的服务费
        map.put("carHygieneMoney",Double.valueOf(String.format("%.2f",carHygieneMoney)));
        //获取订单总租金
        map.put("AlldayMoney",Double.valueOf(String.format("%.2f",AlldayMoney)));
        //获取押金
        map.put("orderDeposit",Double.valueOf(String.format("%.2f",order.getOrderDeposit())));
        //应当支付的总租金
        double allP=CarSunP+OEP+carHygieneMoney+AlldayMoney;
        map.put("allP",Double.valueOf(String.format("%.2f",allP)));
        return map;
    }

    /**
     * 收取租金之后执行
     * @param out_trade_no
     * @param total_amount
     * @return
     */
    @ResponseBody
    @RequestMapping("/ZJPriceYes")
    public ModelAndView ZJPriceYes(String out_trade_no,String total_amount){
        ModelAndView mv= new ModelAndView();
        Check  check = new Check();
        check.setCheckId((String) out_trade_no);
        ResultMsg resultMsg = checkServiceimpl.checkquery(check);
        check = (Check) resultMsg.getEntityObj();

        Order order = orderServiceImpl.selectById(check.getOrderID());

        order.setOrderRentPrice(Double.valueOf(total_amount));
        order.setOrderState(9);
        System.out.println("原押金："+order.getOrderDeposit());
        order.setOrderDeposit(order.getOrderDeposit()+order.getOrderRentPrice());
        System.out.println("租金："+order.getOrderRentPrice());
        System.out.println("总押金："+order.getOrderDeposit());
        int i = orderServiceImpl.updataOrder(order);
        if(i>0){
            resultMsg.setMsg(resultMsg.getMsg()+",修改信息成功");
        }else{
            resultMsg.setMsg(resultMsg.getMsg()+",修改信息失败");
        }
        mv.setViewName("result");
        mv.addObject("resultMsg",resultMsg);
        return mv;
    }

    /**
     * 补足租金之后执行
     * @param out_trade_no
     * @param total_amount
     * @return
     */
    @ResponseBody
    @RequestMapping("/SZJPriceYes")
    public ModelAndView SZJPriceYes(String out_trade_no,String total_amount){
        ModelAndView mv= new ModelAndView();
        TReturn  tReturn = new TReturn();
        tReturn.setReturnId(out_trade_no);
        ResultMsg resultMsg = tReturnServiceImpl.SelectOneQuery(tReturn);
        tReturn = (TReturn) resultMsg.getEntityObj();
        ResultMsg resultMsg1 = tReturnServiceImpl.UpdateTReturnflag(tReturn);

        Order order = orderServiceImpl.selectById(tReturn.getOrderId());
        order.setOrderState(6);
        int i = orderServiceImpl.updataOrder(order);
        if(i>0){
            resultMsg.setMsg("退还金额成功,修改信息成功");
        }else{
            resultMsg.setMsg("退还金额成功,修改信息失败");
        }
        mv.setViewName("result");
        mv.addObject("resultMsg",resultMsg);
        return mv;
    }

    /**
     * 退回租金之后运行
     * @param out_trade_no
     * @param refund_fee
     * @return
     */
    @ResponseBody
    @RequestMapping("/RZJPriceYes")
    public ModelAndView RZJPriceYes(String out_trade_no,String refund_fee){
        ModelAndView mv= new ModelAndView();
        TReturn  tReturn = new TReturn();
        tReturn.setOrderId(out_trade_no);
        ResultMsg resultMsg = tReturnServiceImpl.SelectOneByOrderIdQuery(tReturn);
        tReturn = (TReturn) resultMsg.getEntityObj();
        tReturn.setReturnPrice(Double.valueOf(refund_fee));
        ResultMsg resultMsg1 = tReturnServiceImpl.UpdateTReturnflag(tReturn);

        Order order = orderServiceImpl.selectById(tReturn.getOrderId());
        order.setOrderState(6);
        int i = orderServiceImpl.updataOrder(order);
        if(i>0){
            resultMsg.setMsg("退还金额成功，修改信息成功，总退还金额为:"+refund_fee);
        }else{
            resultMsg.setMsg("退还金额成功，修改信息失败,总退还金额为:"+refund_fee);
        }
        mv.setViewName("result");
        mv.addObject("resultMsg",resultMsg);
        return mv;
    }

    /**
     * 押金支付完毕执行
     * @param out_trade_no
     * @param total_amount
     * @param type_DepositState
     * @return
     */
    @ResponseBody
    @RequestMapping("/YJPriceYes")
    public ModelAndView YJPriceYes(String out_trade_no,String total_amount,String type_DepositState){
        ModelAndView mv= new ModelAndView();
        Order order = new Order();
        order.setOrderId(out_trade_no);
        ResultMsg resultMsg =new ResultMsg();
        if(type_DepositState==null){
            order.setOrderDepositState(2);
        }else{
            order.setOrderDepositState(1);
        }
        int i = orderServiceImpl.updataOrderDepositState(order);
        if(i>0){
            resultMsg.setMsg("押金支付完成，状态修改完成");
        }else{
            resultMsg.setMsg("押金支付完成，状态修改失败");
        }
        mv.setViewName("result");
        mv.addObject("resultMsg",resultMsg);
        return mv;
    }

    /**
     * 退还押金或补足押金——现金
     * @param orderId
     * @param ReturnPrice
     * @param ReturnReason
     * @param Returnrequest
     * @return
     * @throws UnsupportedEncodingException
     * @throws AlipayApiException
     */
    @ResponseBody
    @RequestMapping("/TuiHuanYJXJ")
    public ModelAndView TuiHuanYJXJ(String orderId, String ReturnPrice, String ReturnReason, String Returnrequest) throws UnsupportedEncodingException, AlipayApiException {
        ModelAndView mv =new ModelAndView();
        Order order = orderServiceImpl.selectById(orderId);
        double price = Double.parseDouble(ReturnPrice);

        TReturn tReturn = new TReturn();
        tReturn.setOrderId(orderId);
        tReturn.setReturnFlag("1");
        tReturn.setReturnPrice(price);
        ResultMsg resultMsg = tReturnServiceImpl.InsertTReturn(tReturn);

        order.setOrderState(6);
        int i = orderServiceImpl.updataOrder(order);
        if(i>0){
            if(price>0){
                resultMsg.setMsg(resultMsg.getMsg()+",修改信息成功，退款完成，订单已结束");
            }else{
                resultMsg.setMsg(resultMsg.getMsg()+",修改信息成功，欠款已付清完成，订单已结束");
            }
        }else{
            resultMsg.setMsg(resultMsg.getMsg()+",修改信息失败");
        }
        mv.setViewName("result");
        mv.addObject("resultMsg",resultMsg);
        return mv;
    }

    /**
     * 退还押金或补足押金——支付宝
     * @param orderId
     * @param ReturnPrice
     * @param ReturnReason
     * @param Returnrequest
     * @return
     * @throws UnsupportedEncodingException
     * @throws AlipayApiException
     */
    @ResponseBody
    @RequestMapping("/TuiHuanYJZFB")
    public ModelAndView TuiHuanYJZFB(String orderId, String ReturnPrice, String ReturnReason, String Returnrequest) throws UnsupportedEncodingException, AlipayApiException {
        ModelAndView mv =new ModelAndView();
        double price = Double.parseDouble(ReturnPrice);
        TReturn tReturn = new TReturn();
        tReturn.setOrderId(orderId);
        tReturn.setReturnFlag("0");
        tReturn.setReturnPrice(price);
        ResultMsg resultMsg = tReturnServiceImpl.InsertTReturn(tReturn);
        tReturn = (TReturn) resultMsg.getEntityObj();

        if(price>0){
            mv.setViewName("redirect:/TuiHuanYJ");
            mv.addObject("orderId",orderId);
            mv.addObject("ReturnPrice",price);

        }else{
            mv.setViewName("redirect:/BuZuZJin");
            mv.addObject("orderId",tReturn.getReturnId());
            mv.addObject("ReturnPrice",-price);

        }

        mv.addObject("ReturnReason",ReturnReason);
        mv.addObject("Returnrequest","退还押金");//new Date().toLocaleString()

        return mv;
    }



}
